﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using Framework.Common.Attributes;
using Framework.Serializer;
namespace Framework.Sample
{
    [OrderedDesc("4)    simple orm mapping(反射)")]
    class Test4 : ITest
    {
        public void Run()
        {
            Console.WriteLine(@"simple orm mapping : DataTable or DbReader To Entity");
            //prepare data
            DataTable dt = new DataTable();
            dt.Columns.Add("Name");
            dt.Columns.Add("Age", typeof(int));
            dt.Columns.Add("Id", typeof(int));
            dt.Rows.Add(new object[] { "name11", 88, 11 });
            dt.Rows.Add(new object[] { "name21", 88, 21 });
            dt.Rows.Add(new object[] { "name31", 88, 31 });
            dt.Rows.Add(new object[] { "name41", 88, 41 });

            //get
            var list = ConvertToList1<Person>(dt);
            Console.WriteLine(list.Count);

            //add
            string sql = Add(list[0]);
            Console.WriteLine(sql);
        }


        private List<T> ConvertToList1<T>(DataTable dt) where T : new()
        {
            List<T> list = new List<T>();
            var props = typeof(T).GetProperties();
            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                foreach (var prop in props)
                {
                    prop.SetValue(t, dr[prop.Name], null);
                }
                list.Add(t);
            }
            return list;
        }

        private string Add<T>(T t) where T : class
        {
            var props = typeof(T).GetProperties();
            string tmp = "insert into " + typeof(T).Name;
            tmp += "(";
            for (int i = 0; i < props.Length; i++)
            {
                tmp += props[i].Name;
                if (i != props.Length - 1)
                {
                    tmp += ",";
                }

            }
            tmp += ") values (";
            for (int i = 0; i < props.Length; i++)
            {
                if (props[i].PropertyType == typeof(string))
                {
                    tmp += "'" + props[i].GetValue(t, null) + "'";
                }
                else
                {
                    tmp += props[i].GetValue(t, null);
                }
                if (i != props.Length - 1)
                {
                    tmp += ",";
                }
            }
            tmp += ")";
            return tmp;
        }
    }

    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }


}
